<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="elements"
        @submit="handleSearch"
        @reset="handlerReset"
      >
        <Button icon="add" type="plain" @click="handleAdd">新增</Button>
      </FilterForm>
    </Container>
    <Container height="fill">
      <div class="wraper">
        <Table
          :columns="tableColumns"
          :loading="tableLoading"
          :data="tableData"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize,
          }"
          @paginationChange="pageChange"
        >
          <template #status="{ row }">
            <el-switch
              v-model="row.status"
              active-color="#2178FB"
              :active-value="1"
              :inactive-value="0"
              @change="handleSwitch(row)"
            />
          </template>
          <template #caozuo="{ row }">
            <Tooltip content="编辑" icon="edit" @click="handleEdit(row)" />
            <Tooltip content="删除" icon="delete" @click="handleDelete(row)" />
            <Tooltip
              content="修改密码"
              icon="icon-zhongzhimima"
              @click="handlePwdReset(row)"
            />
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        :title="title"
        :visible.sync="showDrawer"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <el-form
          v-if="showDrawer"
          ref="drawerForm"
          :model="drawerForm"
          :rules="drawerRules"
          label-width="120px"
          size="mini"
          class="demo-drawerForm"
        >
          <el-form-item label="工号：" prop="code">
            <el-input
              v-model.trim="drawerForm.code"
              placeholder="请输入"
              maxlength="20"
              clearable
            />
          </el-form-item>
          <el-form-item label="姓名：" prop="name">
            <el-input
              v-model.trim="drawerForm.name"
              placeholder="请输入"
              maxlength="20"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系方式：">
            <el-input
              v-model.trim="drawerForm.phone"
              placeholder="请输入"
              maxlength="11"
              clearable
            />
          </el-form-item>
          <el-form-item label="所属核算单元：" prop="accountingId">
            <el-select
              v-model="drawerForm.accountingId"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="角色：" prop="roleId">
            <el-select
              v-model="drawerForm.roleId"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in elements[1].options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <template v-if="btnType === 1">
            <el-form-item label="设置密码：" prop="password">
              <el-input
                v-model.trim="drawerForm.password"
                show-password
                placeholder="请输入"
                maxlength="20"
                clearable
              />
            </el-form-item>
            <el-form-item label="确认密码：" prop="confirmPwd">
              <el-input
                v-model.trim="drawerForm.confirmPwd"
                show-password
                placeholder="请输入"
                maxlength="20"
                clearable
              />
            </el-form-item>
          </template>
          <el-form-item label="是否启用：">
            <el-switch
              v-model="drawerForm.status"
              :width="50"
              active-color="#2178FB"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-form>
      </Drawer>
      <Drawer
        :title="title"
        :visible.sync="newShowDrawer"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="newHandleSubmit"
        @cancel="newShowDrawer = false"
      >
        <el-form
          v-if="newShowDrawer"
          ref="drawerFormNew"
          :model="drawerFormNew"
          :rules="drawerRulesNew"
          label-width="120px"
          size="mini"
          class="demo-drawerForm"
        >
          <el-form-item label="新密码：" prop="newPassword">
            <el-input
              v-model.trim="drawerFormNew.newPassword"
              show-password
              placeholder="请输入"
              maxlength="20"
              clearable
            />
          </el-form-item>
          <el-form-item label="确认密码：" prop="newConfirmPwd">
            <el-input
              v-model.trim="drawerFormNew.newConfirmPwd"
              show-password
              placeholder="请输入"
              maxlength="20"
              clearable
            />
            </el-form-item>
        </el-form>
      </Drawer>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  listSysUser,
  getRoles,
  listAllAccountingUnit,
  saveOrUpdateNew,
  removeById,
  updateDictItemStatus,
  resetPassword
} from "@/api/userManage";
export default {
  data() {
    const validePassword = (rule, value, callback) => {
      const reg = /^(?=.*[a-z])(?=.*[A-Z]).{8,20}$/;
      if (value) {
        if (!reg.test(value)) {
          callback(new Error("由8-20位数字、字母、特殊字符组合包含大小写"));
        } else {
          if (this.drawerForm.confirmPwd) {
            if (value !== this.drawerForm.confirmPwd) {
              callback("两次输入的密码不一致");
              return;
            }
          }

          callback();
        }
      } else {
        callback("由8-20位数字、字母、特殊字符组合包含大小写");
      }
    };
    const valideSurePassword = (rule, value, callback) => {
      const reg = /^(?=.*[a-z])(?=.*[A-Z]).{8,20}$/;
      if (value) {
        if (!reg.test(value)) {
          callback(new Error("由8-20位数字、字母、特殊字符组合包含大小写"));
        } else {
          if (this.drawerForm.password) {
            if (value !== this.drawerForm.password) {
              callback("两次输入的密码不一致");
              return;
            }
          }

          callback();
        }
      } else {
        callback("请再次输入密码");
      }
    };
    const validePasswordNew = (rule, value, callback) => {
      const reg = /^(?=.*[a-z])(?=.*[A-Z]).{8,20}$/;
      if (value) {
        if (!reg.test(value)) {
          callback(new Error("由8-20位数字、字母、特殊字符组合包含大小写"));
        } else {
          if (this.drawerFormNew.newConfirmPwd) {
            if (value !== this.drawerFormNew.newConfirmPwd) {
              callback("两次输入的密码不一致");
              return;
            }
          }
          callback();
        }
      } else {
        callback("请再次输入密码");
      }
    };
    const valideSurePasswordNew = (rule, value, callback) => {
      const reg = /^(?=.*[a-z])(?=.*[A-Z]).{8,20}$/;
      if (value) {
        if (!reg.test(value)) {
          callback(new Error("由8-20位数字、字母、特殊字符组合包含大小写"));
        } else {
          if (this.drawerFormNew.newPassword) {
            if (value !== this.drawerFormNew.newPassword) {
              callback("两次输入的密码不一致");
              return;
            }
          }

          callback();
        }
      } else {
        callback("请再次输入密码");
      }
    };
    return {
      deptList: [],
      optionList: [],
      drawerForm: {
        code: "",
        name: "",
        accountingId: '',
        // dataAuth: "",
        password: "",
        confirmPwd: "",
        phone: "",
        roleId: "",
        status: 1,
      },
      drawerRules: {
        code: [{ required: true, message: "请输入工号", trigger: "blur" }],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        accountingId: [
          { required: true, message: "请选择所属核算单元", trigger: "change" },
        ],
        // dataAuth: [
        //   { required: true, message: "请选择数据权限", trigger: "change" },
        // ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
        password: [
          {
            required: true,
            trigger: "blur",
            validator: validePassword,
          },
        ],
        confirmPwd: [
          {
            required: true,
            trigger: "blur",
            validator: valideSurePassword,
          },
        ],
      },
      qrLoading: false,
      showDrawer: false,
      title: "",
      tableColumns: [
        {
          title: "工号",
          dataIndex: "code",
        },
        {
          title: "姓名",
          dataIndex: "name",
        },
        {
          title: "联系方式",
          dataIndex: "phone",
        },
        {
          title: "所属核算单元",
          dataIndex: "accountingName",
          width: 400,
        },
        {
          title: "角色",
          dataIndex: "roleName",
        },
        {
          title: "是否启用",
          dataIndex: "status",
          type: "otherTag",
        },
        {
          title: "操作",
          dataIndex: "caozuo",
          type: "otherTag",
          width: 160,
        },
      ],
      total: 0,
      pageSize: 100,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      btnType: 1,
      elements: [
        {
          label: "综合搜索",
          type: "input",
          key: "comprehensiveSearch",
          value: "",
          placeholder: "请输入工号/姓名/联系方式",
          width: 180,
        },
        {
          label: "角色",
          key: "roleName",
          type: "select",
          itemLabel: "roleName",
          itemValue: "id",
          hideSelectAll: true,
          options: [],
          value: "",
        },
      ],
      newShowDrawer: false,
      drawerFormNew: {
        newPassword: '',
        newConfirmPwd: ''
      },
      drawerRulesNew: {
        newPassword: [
          {
            required: true,
            trigger: "blur",
            validator: validePasswordNew,
          },
        ],
        newConfirmPwd:[
          {
            required: true,
            trigger: "blur",
            validator: valideSurePasswordNew,
          },
        ]
      },
      userId: ''
    };
  },
  created() {
    this.getSelect();
  },
  methods: {
    // 下拉框
    getSelect() {
      getRoles().then((res) => {
        if (res.code === 200) {
          this.elements[1].options = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
      // 核算单元
      listAllAccountingUnit().then((res) => {
        if (res.code === 200) {
          this.deptList = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 是否启用
    handleSwitch(row) {
      updateDictItemStatus({
        userId: row.id,
        status: row.status,
      }).then((res) => {
        if (res.code === 200) {
          this.getData();
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 新增、编辑--保存
    handleSubmit() {
      this.$refs["drawerForm"].validate((valid) => {
        if (valid) {
          if (this.drawerForm.phone) {
            if (!/^(1[0-9]\d{9})$/.test(this.drawerForm.phone)) {
              this.$message.warning("联系方式输入格式不正确");
              return;
            }
          }
          const param = {
            ...this.drawerForm,
          };
          param.roleName = this.elements[1].options.find(
            (item) => item.id === this.drawerForm.roleId
          )?.roleName;
          param.accountingName = this.deptList.find(
            (item) => item.id === this.drawerForm.accountingId
          )?.name;

          if (this.btnType === 2) {
            // 编辑
            this.$delete(param, "password");
            param.id = this.currentRow?.id;
          }
          this.$delete(param, "confirmPwd");
          this.qrLoading = true;
          saveOrUpdateNew(param).then((res) => {
            this.qrLoading = false;
            if (res.code === 200) {
              this.getData();
              this.showDrawer = false;
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.currentPage = 1;
      this.getData(value);
    },
    // 重置
    handlerReset(val) {
      this.handleSearch(val);
    },
    handleEdit(row) {
      // 编辑
      this.currentRow = row;
      this.handleSetForm(row);
      this.btnType = 2;
      this.title = "编辑用户";
      this.showDrawer = true;
    },
    handleSetForm(row) {
      this.$handleSetForm(this.drawerForm, 1, row);
      // this.drawerForm.accountingId = row.accountingName;
    },
    // 修改密码
    handlePwdReset(row) {
      this.userId = row.id
      this.$handleSetForm(this.drawerFormNew, 1, row);
      this.newShowDrawer = true
    },
    newHandleSubmit() {
      this.$refs["drawerFormNew"].validate((valid) => {
        if (valid) {
          const param = {
            userId: this.userId,
            password: this.drawerFormNew.newPassword
          };
          this.$delete(param, "newPassword");
          this.qrLoading = true;
          resetPassword(param).then((res) => {
            this.qrLoading = false;
            if (res.code === 200) {
              this.getData();
              this.newShowDrawer = false;
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleDelete(row) {
      // 删除
      this.$ckConfirm({
        content: "此操作将删除该条记录，并无法恢复， 是否继续?",
        title: "提示",
        okFn: (res) => {
          removeById({
            userId: row.id,
          }).then((res) => {
            if (res.code === 200) {
              this.currentPage = 1;
              this.getData();
              this.$message.success(res.message);
            } else {
              this.$message.error(res.message);
            }
          });
        },
        cancelFn: (res) => {
          console.log("取消");
        },
      });
    },
    // 新增
    handleAdd() {
      this.btnType = 1;
      this.title = "新增用户";
      this.$handleSetForm(this.drawerForm, 0);
      this.drawerForm.accountingId = '';
      this.drawerForm.status = 1;
      this.showDrawer = true;
    },
    // 数据
    getData() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        name: this.newCondition.comprehensiveSearch,
        roleId: this.newCondition.roleName,
      };
      this.tableLoading = true;
      listSysUser(params)
        .then((res) => {
          this.tableLoading = false;
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 分页
    pageChange(payload) {
      this.currentPage = payload.current;
      this.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>
<style lang="less" scoped>
.wraper {
  display: flex;
  height: 100%;
  overflow: hidden;
  .upload-demo {
    .buttons {
      margin: 0px 5px;
      height: 27px;
      margin-top: -1px;
    }
  }
}
</style>
